package com.leyou.filters;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static com.leyou.auth.constants.JwtConstants.COOKIE_NAME;

@Slf4j
@Component
@Order
public class RefreshFilter implements GlobalFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求信息
        ServerHttpRequest request = exchange.getRequest();
        //获取cookies
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        //获取jwt
        HttpCookie cookie = cookies.getFirst(COOKIE_NAME);
        if (cookie == null) {
            //为空，未登录，直接放行
            return chain.filter(exchange);
        }
        String jwt = cookie.getValue();
        //判断是否为空
        if (StringUtils.isBlank(jwt)) {
            //为空，未登录，直接放行
            return chain.filter(exchange);
        }
        try {
            //解析jwt,必须try，不能报错，直接放行即可
            Payload payload = jwtUtils.parseJwt(jwt);
            //获取用户信息，用户id
            UserDetails user = payload.getUserDetails();
            Long userId = user.getId();
            //调用方法，传入用户id，刷新
            jwtUtils.refreshJwt(userId);
        } catch (Exception e) {
            //不报错，直接放行即可
        }
        //放行
        return chain.filter(exchange);
    }
}
